<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\App\WorkContact\Action\Dashboard;

use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use MoChat\App\Common\Middleware\DashboardAuthMiddleware;
use MoChat\App\Rbac\Middleware\PermissionMiddleware;
use MoChat\App\WorkContact\Logic\IndexLogic;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;

/**
 * 客户列表.
 *
 * Class Index
 * @Controller
 */
class IndexSelect extends AbstractAction
{
    /**
     * @Inject
     * @var IndexLogic
     */
    protected $indexLogic;

    /**
     * @Middlewares({
     *     @Middleware(DashboardAuthMiddleware::class),
     * })
     * @RequestMapping(path="/dashboard/workContact/indexSelect", methods="GET")
     */
    public function handle()
    {
        $corpId = user()['corpIds'];
        if (count($corpId) != 1) {
            throw new CommonException(ErrorCode::INVALID_PARAMS, '请先选择企业');
        }

        // 接收参数
        $params = $this->request->all();
        if (empty($params['clientId'])){
            throw new CommonException(ErrorCode::INVALID_PARAMS, 'clientId参数错误');
        }
        $contact_ids= Db::table('client_contact_pivot')
            ->where('client_id', $params['clientId'])
            ->whereNull('deleted_at')
            ->pluck('contact_id')->toArray();
        if (empty($contact_ids)){
            return [];
        }
        return Db::table('work_contact')
            ->whereIn('id',$contact_ids)
            ->when($params['keyword'] !== '', function ($query) use ($params) {
                $query->where('name', 'like', '%' . $params['keyword'] . '%');
            })
            ->select(['name', 'id'])
            ->get()->toArray();
    }
}
